import { VisualizationEvent } from "../components/FeatureProcessor";

export class BorderLineLayer {
  private canvas: HTMLCanvasElement;
  private ctx: CanvasRenderingContext2D;
  private isPlaying: boolean = false;
  private animationFrameId: number | null = null;
  private borderColor: string = 'rainbow'; // 初始颜色
  private colorChangeIntensity: number = 0; // 颜色变化强度

  constructor(canvas: HTMLCanvasElement) {
    this.canvas = canvas;
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      throw new Error('Unable to get 2D context');
    }
    this.ctx = ctx;
  }

  public update(event: VisualizationEvent): void {
    if (!this.isPlaying) return;

    // 根据音频特征计算颜色变化强度
    // 结合RMS能量和频谱质心来驱动颜色变化
    const rmsNormalized = Math.min(1, event.rms / 0.1);
    const centroidNormalized = Math.min(1, event.spectralCentroid / 8000);
    
    // 综合强度基于RMS和频谱质心
    this.colorChangeIntensity = (rmsNormalized * 0.7 + centroidNormalized * 0.3);
    
    // 绘制边框线条
    this.draw();
  }

  private draw(): void {
    const width = this.canvas.width;
    const height = this.canvas.height;
    const borderWidth = 10; // 边框宽度10像素

    this.ctx.save();
    
    // 根据强度和时间生成颜色
    const timeFactor = Date.now() / 1000;
    const hue = (timeFactor * 30 + this.colorChangeIntensity * 360) % 360;
    const saturation = 80 + this.colorChangeIntensity * 20; // 饱和度随强度变化
    const lightness = 50 + this.colorChangeIntensity * 30; // 亮度随强度变化
    
    // 设置边框颜色
    this.ctx.fillStyle = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
    
    // 绘制四条边框线
    // 顶部边框
    this.ctx.fillRect(0, 0, width, borderWidth);
    
    // 底部边框
    this.ctx.fillRect(0, height - borderWidth, width, borderWidth);
    
    // 左侧边框
    this.ctx.fillRect(0, 0, borderWidth, height);
    
    // 右侧边框
    this.ctx.fillRect(width - borderWidth, 0, borderWidth, height);
    
    this.ctx.restore();
  }

  public play(): void {
    this.isPlaying = true;
    this.animate();
  }

  public pause(): void {
    this.isPlaying = false;
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
      this.animationFrameId = null;
    }
  }

  private animate(): void {
    if (!this.isPlaying) return;
    this.animationFrameId = requestAnimationFrame(() => this.animate());
  }

  public resize(width: number, height: number): void {
    this.canvas.width = width;
    this.canvas.height = height;
  }
}